package com.dh.al.al.bdsa;

import org.junit.Assert;
import org.junit.Test;

import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName: BitMapTest
 * @Description: 简单的bitmap测试
 * @Author: shouzimu
 * @Date: 2021/11/24 10:41
 */
public class BitMapTest {

    class TBitMap {
        int[] words;
        int max;

        public TBitMap(int max) {
            this.words = new int[max / Integer.SIZE + 1];
            this.max = max;
        }

        public void set(int n) {
            int arrayIndex = n / Integer.SIZE;
            int bitIndex = n % Integer.SIZE;
            words[arrayIndex] |= 1 << bitIndex;
        }

        public boolean get(int n) {
            int arrayIndex = n / Integer.SIZE;
            int bitIndex = n % Integer.SIZE;
            return (words[arrayIndex] & 1 << bitIndex) != 0;
        }

        public List<Integer> getValue() {
            List<Integer> integerList = new ArrayList<>();
            for (int i = 0; i < words.length; i++) {
                int v = words[i];
                if (v != 0) {
                    for (int j = 0; j < Integer.SIZE; j++) {
                        if (((v >> (j + 1)) & 1) == 1) {
                            integerList.add(i * Integer.SIZE + j + 1);
                        }
                    }
                }
            }
            return integerList;
        }
    }

    @Test
    public void TBitMapTest() {
        TBitMap map1 = new TBitMap(Integer.MAX_VALUE);
        map1.set(10086);
        map1.set(1001186);
        Assert.assertEquals(true, map1.get(10086));
        List<Integer> integerList = map1.getValue();
        for (Integer integer : integerList) {
            System.out.println("v---- " + integer);
        }
    }
}
